﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFServer.Collections
{
    class TimeDependedDictionary<T1, T2>: Dictionary<T1, T2>
    {
        int liveTime, curTime;
        Dictionary<T1, int> times;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="liveTime">in ms</param>
        public TimeDependedDictionary(int liveTime)
            : this(liveTime, liveTime) { }

        public TimeDependedDictionary(int liveTime, int curTime)
        {
            this.liveTime = liveTime;
            this.curTime = curTime;
            times = new Dictionary<T1, int>();
        }

        public new void Add(T1 key, T2 value)
        {
            if (base.ContainsKey(key))
            {
                base[key] = value;
                times[key] = Environment.TickCount;
            }
            else
            {
                base.Add(key, value);
                times.Add(key, Environment.TickCount);
            }
        }

        public new void Remove(T1 key)
        {
            base.Remove(key);
            times.Remove(key);
        }

        public bool IsCurrent(T1 key)
        {
            try
            {
                int dt = Environment.TickCount - times[key];
                if (dt > liveTime)
                    Remove(key);
                return (dt <= curTime);
            }
            catch
            {
                return false;
            }
        }

        public new T2 this[T1 key]
        {
            get
            {
                if (Environment.TickCount - times[key] > liveTime)
                    Remove(key);
                return base[key];
            }
        }
    }
}
